/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package autoUpdate.albumList;

import autoUpdate.UpdateManager;
import autoUpdate.WatchEntry;
import com.google.gdata.data.photos.AlbumEntry;
import com.google.gdata.util.ServiceException;
import configuration.ConfigurationManager;
import configuration.PicasaAccount;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import picasaphotomanager.JFrames.MainJFrame;
import picasaphotomanager.PicasaSessionManager;
import picasaphotomanager.PicasawebClient;

/**
 *
 * @author paskud
 */
public class AlbumListUpdateThread extends Thread {
    private Boolean _enabled = true;
    private ArrayList<IAlbumListUpdateListener> _subscribers = new ArrayList<IAlbumListUpdateListener>();

    @Override
    public void run() {
        _enabled= true;
        
        while (_enabled)
        {
            //Fetch albums
            for (PicasaAccount account : ConfigurationManager.GetPreferences().getUserAccounts())
            {
                PicasawebClient client = PicasaSessionManager.GetClient(account.getId());
                List<AlbumEntry> albums = null;
                try {
                    albums = client.getAlbums();
                } catch (IOException ex) {
                    Logger.getLogger(MainJFrame.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ServiceException ex) {
                    Logger.getLogger(MainJFrame.class.getName()).log(Level.SEVERE, null, ex);
                }

                if (albums == null) continue;

                for (AlbumEntry album : albums)
                {                    
                    //Need to be relocated ?
                    DefaultListModel model = UpdateManager.getModel();
                    
                    AlbumEntry albumFromModel = null;
                    for (Object modelEntry : model.toArray())
                    {
                        albumFromModel = (AlbumEntry)modelEntry;
                        if (albumFromModel.getId().equals(album.getId()))
                            break;

                        albumFromModel = null;
                    }
                    
                    //Add new album to the model
                    if (albumFromModel == null)
                    {
                        model.addElement(album);
                        Logger.getLogger(AlbumListUpdateThread.class.getName()).log(Level.SEVERE, "New album with Id {0} has been added.", album.getTitle().getPlainText());
                    } //Update album in model
                    else if (albumFromModel.getUpdated().getValue() < album.getUpdated().getValue())
                    {
                        int oldPosition = model.indexOf(albumFromModel);
                        
                        model.removeElement(albumFromModel);   
                        model.insertElementAt(album, oldPosition);
                    }
                    
                    WatchEntry watchedAlbum = UpdateManager.getWatchEntry(album.getId());
                    
                    //Auto add new online albums to the watch list
                    if (watchedAlbum == null && ConfigurationManager.GetPreferences().getAutoSyncNewAlbums()) {
                        String photoFolder = ConfigurationManager.GetPreferences().getDefaultPhotoFolder();
                        String albumName = album.getTitle().getPlainText();
                        String albumLocalPath = (new File(photoFolder, albumName)).getPath();                        

                        watchedAlbum = new WatchEntry(album, albumLocalPath);
                        UpdateManager.WatchAlbum(watchedAlbum);
                    }
                    
                    //Update album content
                    if (watchedAlbum != null && watchedAlbum.getLastUpdatedLocally().getTime() < album.getUpdated().getValue())
                        UpdateManager.UpdateAlbumContent(album);
                    
                }
            }
            
            OnAlbumListUpdate();

            //Pause before another check
            long poolingInterval = ConfigurationManager.GetPreferences().getPoolingInterval();
            try {
                Thread.sleep(poolingInterval);
            } catch (InterruptedException ex) {
                //Exit the application
            }
        }
        
        //Remove all subscribers
        _subscribers.clear();
    }

    /**
     * @return the _enabled
     */
    public Boolean isEnabled() {
        return _enabled;
    }

    /**
     * @param enabled the _enabled to set
     */
    public void setEnabled(Boolean enabled) {
        this._enabled = enabled;
    }

    private void OnAlbumListUpdate() {
        for (IAlbumListUpdateListener subscriber : _subscribers)
            subscriber.AlbumListUpdate(new AlbumListUpdateEvent(this));
    }
    
    public void addAlbumListUpdateListiner(IAlbumListUpdateListener listener)
    {
        _subscribers.add(listener);
    }
}
